package boot.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {

    public static final String SPLIT=",";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        if(parameter!=null){
            ps.setString(i,String.join(SPLIT,parameter));
        }
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if(rs.getString(columnName)==null){
            return null;
        }
        return rs.getString(columnName).split(SPLIT);
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if(rs.getString(columnIndex)==null){
            return null;
        }
        return rs.getString(columnIndex).split(SPLIT);
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if(cs.getString(columnIndex)==null){
            return null;
        }
        return cs.getString(columnIndex).split(SPLIT);
    }
}
